package com.cocos.game;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.adjust.sdk.Adjust;
import com.android.fruitballs2048v2.explorer.BuildConfig;
import com.cocos.lib.CocosHelper;
import com.cocos.lib.CocosJavascriptJavaBridge;
import com.cocos.service.SDKWrapper;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;

public class planet_AndroidClient_poof {
    private static final String TAG = "Ab_AndroidClient_bA";

    public static final String API_AD = "$planet_AD_poof$";
    public static final String API_REQUEST_DATA_AD_TYPE = "$planet_type_poof$";
    public static final String DATA_AD_STATUS = "$planet_status_poof$";


    public static final String API_DEVICE_ID = "$planet_device_id_poof$";
    public static final String DATA_DEVICE_ID = "$planet_device_id_poof$";

    public static final String API_CLIPBOARD = "Ab_set_clipboard_bA";

    public static final String REQUEST_TOKEN = "$planet_cc_token_poof$";
    public static final String REQUEST_DATA = "$planet_data_poof$";


    public static final String API_LOCALLANGUAGE = "$planet_LocalLanguage_poof$";
    public static final String DATA_LOCALLANGUAGE_COUNTRY_CODE = "$planet_countryCode_poof$";
    public static final String DATA_LOCALLANGUAGE_LANGUAGE_CODE = "$planet_languageCode_poof$";



    public static final String API_POP = "$planet_float-pop_poof$";

    public static final String API_OPEN_LINK = "$planet_Link_poof$";
    public static final String REQUEST_DATA_LINK = "$planet_url_poof$";

    public static final String API_FRUIT = "$planet_fruit_poof$";
    public static final String REQUEST_DATA_FRUIT = "$planet_type_poof$";


    public static final String API_TYPE = "$planet_game_type_poof$";
    public static final String DATA_TYPE = "$planet_type_poof$";

    public static final String[] ADJUST_NETWORK_A = {"Unknown Devices", "Untrusted Devices", "Organic"};

    public static void planet_callNative_poof(String api, String params) {
        Log.d(TAG, "CocosCall:" + api + "\n" + params);
        JSONObject request = null;

        try {
            request = new JSONObject(params);
            JSONObject requestData = request.getJSONObject(REQUEST_DATA);

            JSONObject response = new JSONObject();
            response.put(REQUEST_TOKEN, request.getString(REQUEST_TOKEN));
            JSONObject responseData = new JSONObject();
            response.put(REQUEST_DATA, responseData);
            switch (api) {
                case API_TYPE:
                    // 获取AB版本
                    Log.d(TAG, "Adjust.isEnabled: " + Adjust.isEnabled() + " isAdjustInit: " + true + " idfa: " + Adjust.getAdid() + " attr: " + Adjust.getAttribution());
                    responseData.put(DATA_TYPE, getAuditTypeByTime(MApplication.AUDIT_END_TIME));
                    callCocos(api,response);
                    getAuditTypeByAdjust(api, response, responseData);
                    return;
                case API_DEVICE_ID:
                    // 获取设备Id
                    String deviceId = DeviceUtil.getDeviceId();
                    responseData.put(DATA_DEVICE_ID, deviceId);
                    callCocos(api, response);
                    return;
                case API_CLIPBOARD:
                    String text = requestData.getString("Ab_text_bA");
                    setClipboard(MApplication.instance, text);
                    return;
                case API_AD:
                    String adType = requestData.getString(API_REQUEST_DATA_AD_TYPE);
                    // 激励广告
                    if (adType.equals("incentive")) {
                        putAdRequest(API_AD, AdType.Rewarded, request);
                        playAd(AdType.Rewarded);
                    } else if (adType.equals("full-screen")) {
                        putAdRequest(API_AD, AdType.Interstitial, request);
                        playAd(AdType.Interstitial);
                    }
                    return;
                case API_LOCALLANGUAGE:
                    Locale systemLocale;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        systemLocale = MApplication.instance.getResources().getConfiguration().getLocales().get(0);
                    } else {
                        systemLocale = Locale.getDefault();
                    }
                    // 获取设备Id
                    responseData.put(DATA_LOCALLANGUAGE_COUNTRY_CODE, systemLocale.getCountry());
                    responseData.put(DATA_LOCALLANGUAGE_LANGUAGE_CODE, systemLocale.getLanguage());
                    callCocos(api, response);
                    return;
                case API_POP:
                    showPop();
                    return;
            }
        } catch (JSONException e) {
            if (BuildConfig.DEBUG) {
                throw new RuntimeException(e);
            }
        }

    }

    public static void getAuditTypeByAdjust(String api, JSONObject response, JSONObject responseData) throws JSONException {
        if (Adjust.getAttribution() != null && Adjust.getAttribution().network != null) {
            // 2024/8/2  获取归因成功埋点
            String abType = getAuditByAdjustNetwork(Adjust.getAttribution().network);
            NetHelper.getInstance().logAppType("A".equals(abType) ? NetHelper.ABResultType.FAIL : NetHelper.ABResultType.SUCCESS, Adjust.getAttribution().network);
//            responseData.put(DATA_TYPE, abType);
//            callCocos(api, response);
        } else {
            final Handler handler = new Handler(Looper.getMainLooper());
            final AtomicLong elapsedTime = new AtomicLong(0); // To track elapsed time
            Log.d(TAG, "getAuditTypeByAdjust: " + Adjust.getAttribution());
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "getAuditTypeByAdjust: " + Adjust.getAttribution());
                    if (elapsedTime.get() >= 10 * 1000) { // Check if 10 seconds have passed
                        handler.removeCallbacks(this); // Remove this callback to stop further executions
                        NetHelper.getInstance().logAppType(NetHelper.ABResultType.DELAY, null);
//                        try {
//                            responseData.put(DATA_TYPE, getAuditByAdjustNetwork(ADJUST_NETWORK_A[0]));
//                            callCocos(api, response);
//                        } catch (JSONException ignored) {
//                        }
                        return;
                    }
                    elapsedTime.addAndGet(300); // Increment by 100ms on each execution

                    if (Adjust.getAttribution() != null && Adjust.getAttribution().network != null) {
                        String abType = getAuditByAdjustNetwork(Adjust.getAttribution().network);
                        NetHelper.getInstance().logAppType("A".equals(abType) ? NetHelper.ABResultType.FAIL : NetHelper.ABResultType.SUCCESS, Adjust.getAttribution().network);
//                        try {
//                            responseData.put(DATA_TYPE, abType);
//                            callCocos(api, response);
//                        } catch (JSONException ignored) {
//                        }
                        handler.removeCallbacks(this); // Remove this callback to stop further executions
                    } else {
                        handler.postDelayed(this, 100);
                    }
                }
            };
            handler.postDelayed(runnable, 300);
        }
    }

    public static String getAuditByAdjustNetwork(String network) {
        for (String s : ADJUST_NETWORK_A) {
            if (s.equals(network)) {
                return "A";
            }
        }
        return "B";
    }

    public static String getAuditTypeByTime(String auditEndTime) {
        long currentTimeMillis = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        try {
            // 将指定时间字符串转换为Date对象
            Date dateSpecified = sdf.parse(auditEndTime);
            // 比较当前时间和指定时间
            assert dateSpecified != null;
            if (currentTimeMillis > dateSpecified.getTime()) {
                Log.d(TAG, "当前时间晚于指定时间");
                return "B";
            } else {
                Log.d(TAG, "当前时间早于指定时间");
                return "A";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "B";
    }

    private static void callCocos(String api, JSONObject response) {
        Log.d(TAG, "CallCocos:" + api + "\n" + response);
        CocosHelper.runOnGameThread(() -> CocosJavascriptJavaBridge.evalString("AndroidClient.response('"
                + api
                + "','"
                + response
                + "')"));
    }


    public static void DebugResponse(String api, String params) throws JSONException {
        Log.d(TAG, "CocosCall DebugResponse:" + api + "\n" + params);
        JSONObject jsonObject = new JSONObject(params);
        JSONObject response = new JSONObject();

        JSONObject data = jsonObject.getJSONObject("data");
        data.put("javaType", "123456");
        response.put("cc_token", jsonObject.getString("cc_token"));
        response.put("data", data);
        Log.d(TAG, "CocosCall res: " + "AndroidClient.response("
                + api + ","
                + response
                + ")");
    }

    public static void setClipboard(Context context, String text) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard != null) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
                // For versions lower than Honeycomb, use the deprecated setText method.
                clipboard.setText(text);
            } else {
                ClipData clip = ClipData.newPlainText("Copied Text", text);
                clipboard.setPrimaryClip(clip);
            }
        }
    }

    public static void playAd(AdType adType) {
        Log.d(TAG, "playAd:" + adType.name());

        if (SDKWrapper.shared().getActivity() instanceof BaseAdActivity) {
            Handler mainHandler = new Handler(Looper.getMainLooper());
            // 使用主线程的Handler更新UI
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    BaseAdActivity baseAdActivity = (BaseAdActivity) SDKWrapper.shared().getActivity();
                    if (adType == AdType.Rewarded) {
                        baseAdActivity.showRewardedAd();
                    } else if (adType == AdType.Interstitial) {
                        baseAdActivity.showInterstitialAd();
                    }
                }
            }, 1800);

        } else {
            if (BuildConfig.DEBUG) {
                throw new RuntimeException("AdActivity is not BaseAdActivity");
            }
        }
    }

    public static void showPop() {
        Log.d(TAG, "showPop");
        if (SDKWrapper.shared().getActivity() instanceof BaseAdActivity) {
            // 主线程中的Handler
            Handler mainHandler = new Handler(Looper.getMainLooper());
            // 使用主线程的Handler更新UI
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    // 更新UI的代码
                    BaseAdActivity baseAdActivity = (BaseAdActivity) SDKWrapper.shared().getActivity();
                    baseAdActivity.showPop();
                }
            });

        } else {
            if (BuildConfig.DEBUG) {
                throw new RuntimeException("AdActivity is not BaseAdActivity");
            }
        }
    }

    public static void putAdRequest(String api, AdType adType, JSONObject request) {
        ConcurrentLinkedQueue<JSONObject> queue = MApplication.getRequestQueue(api + adType.name());
        boolean result = queue.offer(request);
        Log.d(TAG, "putAdRequest:" + result + "  queueName:" + api + adType.name() + " \nrequest:" + request);

    }

    public static void onAdPlayError(AdType adType) {

        JSONObject request = MApplication.getRequestQueue(API_AD + adType.name()).poll();
        Log.d(TAG, "queueName:" + API_AD + adType.name() + " \nrequest:" + request);

        if (request == null) {
            return;
        }
        JSONObject response = new JSONObject();
        try {
            response.put(REQUEST_TOKEN, request.getString(REQUEST_TOKEN));
            JSONObject data = new JSONObject();
            data.put(DATA_AD_STATUS, "ad-error");
            response.put(REQUEST_DATA, data);
            planet_AndroidClient_poof.callCocos(API_AD, response);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

    }

    public static void onAdPlayOver(AdType adType) {

        JSONObject request = MApplication.getRequestQueue(API_AD + adType.name()).poll();
        Log.d(TAG, "queueName:" + API_AD + adType.name() + " \nrequest:" + request);
        if (request == null) {
            return;
        }
        JSONObject response = new JSONObject();
        try {
            response.put(REQUEST_TOKEN, request.getString(REQUEST_TOKEN));
            JSONObject data = new JSONObject();
            data.put(DATA_AD_STATUS, "ad-over");
            response.put(REQUEST_DATA, data);
            planet_AndroidClient_poof.callCocos(API_AD, response);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

}